package org.example.rental.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.rental.common.Result;
import org.example.rental.domain.Car;
import org.example.rental.domain.RentalGoods;
import org.example.rental.service.CarService;
import org.example.rental.service.RentalGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/car")
public class CarController extends BaseController{


    @Autowired
    CarService carService;

    @Autowired
    RentalGoodsService rentalGoodsService;


    @GetMapping("/info/{id}")
    public Result info(@PathVariable(name = "id") Long id){
        Car car = carService.getById(id);

        return Result.succ(car);
    }

    @GetMapping("/list")
    public Result list(String vehNum,String name,String carNum,String status){
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(vehNum),"veh_num",vehNum)
                .eq(StrUtil.isNotBlank(carNum),"car_num",carNum)
                .eq(StrUtil.isNotBlank(status),"status",status)
                .like(StrUtil.isNotBlank(name),"veh_name",name);
        Page<Car> page = carService.page(getPage(), wrapper);

        return Result.succ(page);
    }


    @PostMapping("/save")
    @Transactional
    public Result save(@Validated @RequestBody Car car){
        car.setRegDate(new Date());
        carService.save(car);

        //可租赁最大数量加1
        RentalGoods goods = rentalGoodsService.getOne(new QueryWrapper<RentalGoods>().eq("veh_id", car.getVehId()));
        goods.setSizes(goods.getSizes()==null?1: goods.getSizes()+1);
        rentalGoodsService.updateById(goods);
        return Result.succ(car);
    }


    @PostMapping("/update")
    public Result update(@Validated @RequestBody Car car){
        carService.updateById(car);
        return Result.succ(car);
    }

    @PostMapping("/delete")
    @Transactional
    public Result delete(@RequestBody Long[] ids){
        //删除车辆
        carService.removeByIds(Arrays.asList(ids));


        return Result.succ("车辆删除成功");

    }

    @GetMapping("/selectByVehId")
    public Result selectByVehId(Integer vehId){
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0);
        wrapper.eq("veh_id",vehId);
        List<Car> cars = carService.list(wrapper);
        return Result.succ(cars);
    }






}
